from django.shortcuts import render
from rest_framework.views import APIView
from .models import UserModel
import jwt
from MeiDuo.settings import SECRET_KEY  # 导入 setting中的 秘钥
from rest_framework.response import Response
import datetime


# 定义 登录接口开发
class LoginView(APIView):
    def post(self, request):
        # 获取传递来的用户名 密码
        username = request.POST.get("username")
        password = request.POST.get("password")
        # 进行验证 是否正确是否存在
        user = UserModel.objects.filter(username=username, password=password).first()
        if user:
            info = {
                'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=1),  # 过期时间
                'uid': user.id,
                'username': user.username,
            }
            # 验证通过，进行jwt令牌生成
            token = jwt.encode(info, SECRET_KEY)
            return Response({"msg": "登录成功", "token": token})
        else:
            # 验证失败
            return Response({"msg": "登录失败"}, status=401)


# 定义装饰器函数
def mytest(func):
    def inner(request):
        print("------在进行视图函数操作前 先校验token令牌------")
        token = request.META.get("HTTP_AUTHORIZATION")
        print(token)
        # 解析这个令牌
        try:
            data = jwt.decode(token, SECRET_KEY, algorithms=["HS256"])
            uid = data.get("uid")
        except Exception as e:
            print(e)
            uid = None
        request.COOKIES["uid"] = uid
        return func(request)

    return inner
# 使用django提供的 方法装饰器函数
from django.utils.decorators import method_decorator
# 定义一个测试接口
@method_decorator(mytest, name="dispatch")
class TestView(APIView):
    def get(self, request):
        uid = request.COOKIES["uid"]
        if uid:
            print("开始执行get处理")
            return Response({"msg": "令牌有效"})
        else:
            return Response({"msg": "令牌无效"}, status=401)

    def post(self, request):
        uid = request.COOKIES["uid"]
        if uid:
            print("开始执行post处理")
            return Response({"msg": "令牌有效"})
        else:
            return Response({"msg": "令牌无效"}, status=401)
